import { ChangeEvent, FC, useState } from 'react';
import styles from './index.module.scss';
import { Typography, Button, Space, Input, message } from 'antd';
import { LeftOutlined, EditOutlined, LoadingOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import EditToolbar from '../EditToolbar';
import useGetPageInfo from '../../../../../hooks/useGetPageInfo';
import { changePageTitle } from '../../../../../store/pageInfoReducer';
import { useDispatch } from 'react-redux';
import useGetComponentInfo from '../../../../../hooks/useGetComponentInfo';
import { useRequest, useKeyPress, useDebounceEffect } from 'ahooks';
import { updateQuestionService } from '../../../../../services/question';

const { Title } = Typography;
const EditHeader: FC = () => {
  const { title } = useGetPageInfo();
  const [titleEditable, setTitleEditable] = useState(false);
  const dispatch = useDispatch();
  const nav = useNavigate();
  function handleTitle() {
    setTitleEditable(true);
  }
  const TitleElement = () => {
    function handleChange(event: ChangeEvent<HTMLInputElement>) {
      const newTitle = event.target.value;
      if (!newTitle) return;
      dispatch(changePageTitle(newTitle));
    }
    if (!titleEditable) {
      return (
        <Space>
          <Title level={5}>{title}</Title>{' '}
          <Button icon={<EditOutlined />} type="text" onClick={handleTitle} />
        </Space>
      );
    }
    return (
      <Input
        value={title}
        onChange={handleChange}
        onPressEnter={() => setTitleEditable(false)}
        onBlur={() => setTitleEditable(false)}
      />
    );
  };

  const SaveButton = () => {
    //保存
    const { id } = useParams();
    const { componentList = [] } = useGetComponentInfo();
    const pageInfo = useGetPageInfo();
    const { loading, run: save } = useRequest(
      async () => {
        if (!id) return;
        await updateQuestionService(id, { ...pageInfo, componentList: componentList });
      },
      { manual: true, debounceWait: 1000 },
    );
    //快捷键
    useKeyPress(['ctrl.s', 'meta.s'], (event: KeyboardEvent) => {
      event.preventDefault();
      if (loading) return;
      save();
    });

    useDebounceEffect(
      () => {
        if (loading) return;
        save();
      },
      [componentList, pageInfo],
      {
        wait: 1000,
      },
    );
    return (
      <Button type="default" onClick={save} icon={loading ? <LoadingOutlined /> : null}>
        保存
      </Button>
    );
  };

  const PublicButton = () => {
    const nav = useNavigate();
    //发布
    const { id } = useParams();
    const { componentList = [] } = useGetComponentInfo();
    const pageInfo = useGetPageInfo();
    const { loading, run: pub } = useRequest(
      async () => {
        if (!id) return;
        await updateQuestionService(id, {
          ...pageInfo,
          componentList: componentList,
          isPublished: true,
        });
      },
      {
        manual: true,
        onSuccess: () => {
          message.success('发布成功');
          nav('/question/stat/' + id);
        },
      },
    );

    return (
      <Button type="primary" onClick={pub} disabled={loading}>
        发布
      </Button>
    );
  };
  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <TitleElement />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolbar />
        </div>
        <div className={styles.right}>
          <Space>
            <SaveButton />
            <PublicButton />
          </Space>
        </div>
      </div>
    </div>
  );
};
export default EditHeader;
